﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EntityComponentSystem.Framework
{
    public class ComponentMap
    {
        public string Name { get; private set; }
        public Component Component { get; private set; }

        public ComponentMap(string name, Component component)
        {
            this.Name = name;
            this.Component = component;
        }
    }

    public class ComponentList : IEnumerable<Component>
    {
        private List<ComponentMap> components = new List<ComponentMap>();
        private int entity = 0;

        public int Count { get { return components.Count; } }
        
        public ComponentList(int entity)
        {
            this.entity = entity;
        }

        public void Add(GameEngine ge, string name, Component component)
        {
            components.Add(new ComponentMap(name, component));
            ge.AddToAutoSystems(entity, name);
        }

        public void Remove(GameEngine ge, string name)
        {
            for (int i = this.Count - 1; i >= 0; i--)
            {
                if (components[i].Name == name)
                {
                    ge.RemoveFromAutoSystems(entity, name);
                    components.RemoveAt(i);
                }
            }
        }

        public void Clear(GameEngine ge)
        {
            for (int i = this.Count - 1; i >= 0; i--)
            {
                ge.RemoveFromAutoSystems(entity, components[i].Name);
                components.RemoveAt(i);
            }
        }

        public Component Find(string name)
        {
            var comMap = components.FirstOrDefault(x => x.Name == name);
            if (comMap != null)
                return comMap.Component;
            return null;
        }

        public T Find<T>(string name)
            where T : Component
        {
            var comMap = components.FirstOrDefault(x => x.Name == name);
            if (comMap != null)
                return comMap.Component as T;
            return null;
        }

        public IEnumerator<Component> GetEnumerator()
        {
            foreach (var c in components)
                yield return c.Component;
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            foreach (var c in components)
                yield return c.Component;
        }
    }
}
